<template>
	<ListLayout>
		<CardBaseWrapper>
			<template #head>
				<span style="font-weight: 400;font-size: 28rpx;color: #F56C6C;">*</span>
				故障描述
			</template>
			<template #body>
				<u-input v-model="baseFormData.faultRemark" type="textarea"></u-input>
			</template>
		</CardBaseWrapper>

		<CardAttachment   ref="AttachmentCard"></CardAttachment>


		<CardBaseWrapper  :showBodySlot="timer">
			<template #head>
				<view class="u-flex u-row-between">
					<view class="">
						录音
					</view>
					<view class="">
						
						<HButton v-if="!baseFormData.recording" plain size="small" :block="false" @touchend="onTouchend" @longress="onRecording">
							按住开始录音
							</HButton>
						<template v-if="baseFormData.recording">
						<HButton class="u-margin-right-10" plain size="small" :block="false"  @click="onDelRecording">删除</HButton>
						<HButton  size="small" :block="false" @click="onPlayRecording">播放录音({{seconds}}s)</HButton>
						</template>
					</view>
				</view>


			</template>
			<template #body>  
		
			<view  	v-if="timer" class="u-margin-top-16 u-font-40 u-tips-color u-text-center">
			 录音中... 
			</view> 
			</template>

		</CardBaseWrapper>



		<template v-if="scanCodeConfig.showAcceptDept">

			<CardBaseWrapper>
				<template #head>
					<span style="font-weight: 400;font-size: 28rpx;color: #F56C6C;">*</span>
					工单接单科室
					<span style=" font-weight: 400;font-size: 28rpx;color: #98A5B3;margin-left: 60rpx; ">
						选择此工单由哪些科室处理
					</span>
				</template>
				<template #body>
					<checkbox-group @change="radioGroupChange">
						<label class="radio-label u-p-l-20  u-p-r-20  u-p-t-6 u-p-b-6  u-m-6 "
							v-for="(sub, ind) in handleDepartmentList" :key="sub.deptId">
							<view class="u-flex">
								<view>
									<checkbox color="#409EFF" :checked="ind === 0" :value="sub.deptId" />
								</view>
								<view>{{sub.deptIdToName}}</view>
							</view>
						</label>
					</checkbox-group>
				</template>
			</CardBaseWrapper>
		</template>


		<CardBaseWrapper>
			<template #head>
				其他信息
			</template>
			<template #body>
				<evan-form :model="otherFormData" ref="otherForm">
					<evan-form-item label="故障分类" prop="faultType"> 
						<ItemRow v-model="otherFormData.faultType"   dicKey="faultClassification"
							chooseType="select-dic-cascader"></ItemRow>
					</evan-form-item>
					<evan-form-item label="报修人" prop="user">
						<u-input v-model="otherFormData.user"  placeholder="输入报修人" input-align="right"></u-input>
					</evan-form-item>
					<evan-form-item label="报修电话" prop="phone">
						<u-input v-model="otherFormData.phone" placeholder="输入报修电话" input-align="right"></u-input>
					</evan-form-item>

					<evan-form-item label="报修科室" prop="deptId"> 
						<ItemRow v-model="otherFormData.deptId" ref="department" chooseType="select-department">
						</ItemRow>
					</evan-form-item>
					<evan-form-item label="报修地址" prop="place">
						<u-input input-align="right" type="textarea" v-model="otherFormData.place"
							placeholder="请填写报修地址" />
					</evan-form-item>

				</evan-form>
			</template>
		</CardBaseWrapper>


		<CardBaseWrapper :showBodySlot="isMore">
			<template #head>
				<view class="u-flex u-row-between">
					<view>更多</view>
					<view class="">
						<switch checked="true" :checked="isMore" @change="change($event,2)" color="#409EFF" />
					</view>
				</view>


			</template>
			<template #body>
				<evan-form :model="moreFormData" ref="form">
					<evan-form-item label="实际报修地址" prop="actualRepairPlace">
						<ItemRow v-model="moreFormData.actualRepairPlace" ref="actualRepairPlace"
							chooseType="select-department">
						</ItemRow>
					</evan-form-item>
					<evan-form-item label="紧急程度" prop="degree"> 
						<ItemRow v-model="moreFormData.degree" showDicSelectDefaultValue  dicKey="gradeUrgency" chooseType="select-dic">
						</ItemRow>
					</evan-form-item>
					<evan-form-item label="影响范围" prop="rangeType">
						<ItemRow v-model="moreFormData.rangeType"  showDicSelectDefaultValue  dicKey="faultScope" chooseType="select-dic"></ItemRow>
					</evan-form-item>
					<evan-form-item label="预约维修" prop="isReserve"> 
						<ItemRow v-model="moreFormData.isReserve" chooseType="switch"></ItemRow>
					</evan-form-item> 
					<evan-form-item v-if="moreFormData.isReserve" label="预约维修时间" >
						<ItemRow v-model="moreFormData.responseTime"  chooseType="date-picker"></ItemRow>
					</evan-form-item>
					<evan-form-item   label="完成时间" >
						<ItemRow v-model="moreFormData.completeTime"  chooseType="date-picker-ymd"></ItemRow>
					</evan-form-item>
					<evan-form-item label="资产名称">
						<u-input input-align="right" type="textarea" v-model="moreFormData.equipment"placeholder="请填写故障描述" />
					</evan-form-item>
					<evan-form-item label="资产位置" >
						<ItemRow v-model="moreFormData.equipmentAddressId" ref="department" chooseType="select-department">
						</ItemRow>
					</evan-form-item>
				</evan-form>
			</template>
		</CardBaseWrapper>

		<template v-if="scanCodeConfig.showDealByMyself">
			<CardBaseWrapper :showBodySlot="isMe">
				<template #head>
					<view class="u-flex u-row-between">
						<view class="">
							由我处理
						</view>
						<view class="">
							<switch :disabled="type==2" :checked="isMe" @change="change($event,1)" color="#409EFF" />
						</view>
					</view>
				</template>

				<template #body>
					<evan-form :model="moreFormData" ref="form">
						<evan-form-item label="预计工时(小时)" prop="reqTime">
							<input v-model="moreFormData.reqTime" placeholder-style="color:#98A5B3"   type="digit"   placeholder="请输入预计工时(单位:小时)" />
						</evan-form-item>
					</evan-form>
				</template>
			</CardBaseWrapper>

		</template>



		<wyb-loading @hide="hide" ref="loading" type="rectangle" title="录音播放中" loading-type="scale-line" />
		<template #footer>
			<view class="u-padding-30">
				
			<HButton @click="onSubmit">报修</HButton>
			</view>

		</template>
	</ListLayout>
</template>

<script>
	var time
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	import ItemRow from '@/components/arrow/itemArrow.vue'
	import HButton from '@/components/button/index.vue'
	import wybLoading from '@/components/wyb-loading/wyb-loading.vue'
	import PagesCourseRouterConfig from '@/pagesCourse/routerConfig.js'
	import CardBaseWrapper from '@/components/card/components/cardBaseWrapper.vue'
	import CardAttachment from '@/components/card/attachment.vue'
	import ListLayout from '@/components/layout/listLayout.vue'
	import {
		addReport,
		getHandleDepartment,
		getScanCodeConfig,
		getScanReportData
	} from '../../apis/report';
import { attachmentFormatter } from '../../common/submitFormatter';
import { upLoad } from '../../apis/common';
	export default {
		components: {
			wybLoading,
			ListLayout,
			CardBaseWrapper,
			CardAttachment,
			ItemRow,
			HButton
		},
		data() {
			return {
				
			baseFormData:{
				acceptDeptIdsStr: "",
				faultRemark: '',
				enclosure: "", 
				recording: '',
			},
				otherFormData: {
					deptId: '',
					user: '',
					phone: '',
					faultType: "",
					place: '',
				},
				moreFormData: {
					// 实际报修地址
					actualRepairPlace: "",
					isMyself: 0,
					reqTime: '',
					degree: '',
					rangeType: '',
					isReserve: '',
					responseTime: '',
					deptCode: '',
					hospitalId: '',
					equipment: '',
					equipmentAddressId: "",
					equipmentAddress: '',

				},
				otherRules: {
					faultType: [{
						required: true,
						message: '请选择故障分类',
					}],
					phone:[{
						validator(rule,val,cb){
							if(val){
								const reg =/^(?:(?:\+|00)86)?1[3-9]\d{9}$/
								if(reg.test(val)){
									cb()
								}else{
									cb(new Error('报修电话格式错误'))
								}
							}else{
								cb()
							}
						}
					}]
				},
				rules: {
					faultRemark: [{
						required: true,
						message: '请填写故障描述',
					}],
					acceptDeptIdsStr: [{
						required: true,
						message: '请选择工单接单科室',
					}],

				},


				PagesCourseRouterConfig,
				handleDepartmentList: [],
				scanCodeConfig: {
					// 是否显示由我处理
					showDealByMyself: false,
					// 是否显示接单科室
					showAcceptDept: true
				},
			 
				date: '', 
				head: this.$head,
				isMe: false,
				isMore: false,
				isMake: false,  
				faultType: null, //故障分类
				deptId: null, //报修科室
  

				voicePath: '', //录音地址
				recordstatus: 0,
				seconds: 0, //录音时间
				cloneSeconds:0,
				timer:null,
				enclosure: [], //附件
				username: uni.getStorageSync('username'),
				phone: uni.getStorageSync('phone'),
				hardwareCode: '',
				hardwareName: '',
				responsePlace: '',
				type: 1, //1普通2扫码
				deptCode: '', //扫码信息
				newUser: false,
				hospitalId: '', //医院编码
				acceptDeptId: []
			}
		},
		onLoad(e) {
			console.log(e)
			const {type,value} = e
			this.$nextTick(() => {
				this.$refs.otherForm.setRules(this.otherRules)
				this.$refs.form.setRules(this.rules)
			})
			
			if(type && type=='scan'){
				this.getScanReportData(e)
			}
			
			console.log(e, 'onLoad');
			if (e.hasOwnProperty('type')) {
				this.type = e.type
			}
			if (e.hasOwnProperty('scene')) {
				var scene = decodeURI(e.scene)
				console.log(scene)
				scene = scene.split('%26')
				console.log(scene)
				// this.otherFormData.deptId = scene[1]
				// this.deptCode = scene[1]
				this.hospitalId = scene[0]
				this.otherFormData.deptId =  scene[2] 
				console.log(this.deptCode, this.hospitalId, '-this.hospitalId')
				this.$showloading()
				// 扫码登录需静默登录
				this.wxLogin()

			} else {
				// this.reset()
			} 



			var self = this


			// recorderManager.onStart(() => {
			// 	this.seconds = 0
			// 	this.recorde = ''
			// 	this.recordstatus = 1
			// 	this.voicePath = ''
			// 	time = setInterval(() => {
			// 		this.seconds++
			// 		if (this.seconds >= 60) {
			// 			recorderManager.stop()
			// 		}
			// 	}, 1000)
			// })
			innerAudioContext.onEnded(() => {
				console.log('onEnded');
				this.$refs.loading.hideLoading()
			});
				
			innerAudioContext.onCanplay((res)=>{
				console.log('onCanplay');
			})
			recorderManager.onStop(function(res) {
				uni.showLoading({
					title: '上传中...'
				})
				const {tempFilePath} =res
				upLoad(tempFilePath,'',(data)=>{
					console.log(data,'data');
							let file = data.data;
							file = JSON.parse(file); 
							uni.hideLoading()
							self.baseFormData.recording = file.body.body.url
				})
			 
			});

			this.init()



		},
		beforeDestroy() {
			recorderManager.stop(); 
			uni.removeStorageSync('hospitalId')
		},
		methods: {
				// 删除录音
			onDelRecording(){
				this.baseFormData.recording = ''
					this.seconds =0
			},
			onRecording(){
				console.log('开始录音'); 
				
				recorderManager.start();
				this.seconds=0
				   this.timer = setInterval(()=>{
					this.seconds++
				},1000)
			},
			onTouchend(){
				recorderManager.stop();
				clearInterval(this.timer)
				this.timer = null
				console.log('录音结束');
			},
				// 播放录音
			onPlayRecording() { 
				var src = this.baseFormData.recording
				if (src) {
					var a = src.slice(0, 4)
					if (a === 'http') {
						src = src
					} else if (src) {
						src = uni.getStorageSync('imgUrl') + src
					}
					
				console.log('播放录音',src);
					this.$refs.loading.showLoading() // 显示
					innerAudioContext.src = src;
					innerAudioContext.play();
				 
				}
			},
			radioGroupChange(ev) {
				this.baseFormData.acceptDeptIdsStr = ev.detail.value
			},
			async init() {
				const res = await getHandleDepartment()
				this.handleDepartmentList = res.body || []
				if (this.handleDepartmentList.length) {

					this.baseFormData.acceptDeptIdsStr = [this.handleDepartmentList[0].deptId]
				}

				const res1 = await getScanCodeConfig()
				this.scanCodeConfig = res1.body
			},
			// 获取扫码报修数据
			async getScanReportData(query){ 
			this.isMore  = true
			const {value,equipmentAddressId,equipment} = query
			this.moreFormData.equipmentAddressId = equipmentAddressId
			this.moreFormData.equipment = equipment 
			},

			wxLogin() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log('loginRes', loginRes)
						var code = loginRes.code;
						this.$pop.ajaxPost('/firstLoginWeChat', {
							code
						}).then(res => {
							console.log('登录', res)

							if (res.code == 10) {
								console.log('未注册')
								this.newUser = true
								uni.setStorageSync('hospitalId', this.hospitalId)
								getApp().getdic()
								getApp().getunit()
								getApp().getuser()
								this.reset()
							} else if (res.code == 0) { //注册了用户直接登录
								this.newUser = false
								uni.setStorageSync('token', res.body.token)
								uni.setStorageSync('depts', res.body.depts)
								if (res.body.depts.length > 0) {
									uni.setStorageSync('dept', res.body.depts[0])
								}
								uni.setStorageSync('imgUrl', res.body.INTERNET_FILE_BASE_URL)
								uni.setStorageSync('username', res.body.user)
								uni.setStorageSync('phone', res.body.phone)
								getApp().getdic()
								getApp().getunit()
								getApp().getuser()
								this.reset()
							} else {
								uni.showModal({
									title: res.msg
								})
							}
						})


					}
				})


			},
			reset() {
				uni.hideLoading()
				this.getScope()
				if (!this.newUser) {
					this.otherFormData.user = uni.getStorageSync('username');
					this.otherFormData.phone = uni.getStorageSync('phone');
				} 
 
	

			}, 
			onSubmit(e) { 
				if(!this.baseFormData.faultRemark){
					this.$msg('请输入故障描述！')
					return
				}
				if (this.scanCodeConfig.showAcceptDept) {
					if (!this.baseFormData.acceptDeptIdsStr.length) {
						this.$msg('请选择一个处理科室！')
						return
					}  
				}
			
				this.$refs['otherForm'].validate(async (valid) => {
				 
					if (valid) {
						uni.showLoading({
							title: '提交中...',
							mask: true
						})
						let attachment = this.$refs.AttachmentCard.$data.attachment
						this.baseFormData.enclosure = attachmentFormatter(attachment)
						const data = {
							...this.baseFormData,
							...this.otherFormData, 
							...this.moreFormData,
						}
						if(this.scanCodeConfig.showDealByMyself && this.isMe){
							data.isMyself =1
						}else{
							data.isMyself =0
						}
						if (this.newUser) {
							data.deptCode = this.deptCode
							data.hospitalId = this.hospitalId
						}
						try{
						 
						await addReport(data)
						uni.showModal({
							title: '报修成功',
							success: () => {
								uni.navigateBack({})
							}
						})
							
						}catch(err){
							
						}finally{
							uni.hideLoading()
						}
					}
				}) 
			 
			},
		 
		 
		
			hide() {
				innerAudioContext.stop();
			}, 
			//选择图片
			async chooseImg() {

				var file = await this.$chooseImg(this.hospitalId)

				this.enclosure.push(file)

			},
			//选择视频
			async chooseVideo() {

				var file = await this.$chooseVideo(this.hospitalId)
				this.enclosure.push(file)

			},
			async uploadfile() {

				var file = await this.$uploadfile(this.hospitalId)
				this.enclosure.push(file)

			},


			 
			change(e, type) { 
				switch (type) {
					case 1:
						this.isMe = e.detail.value;
						break;
					case 2:
						this.isMore = e.detail.value;
						break;
					case 3:
						this.isMake = e.detail.value;
						break;
				}
			},
			getScope() {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.camera']) { //获取摄像头权限
							wx.authorize({
								scope: 'scope.camera',
								success() {
									console.log('授权成功')
								},
								fail() {
									wx.showModal({
										title: '提示',
										content: '尚未进行授权，部分功能将无法使用',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												console.log('用户点击确定')
												wx.openSetting({ //这里的方法是调到一个添加权限的页面，可以自己尝试
													success: (res) => {
														if (!res.authSetting[
																'scope.camera']) {
															wx.authorize({
																scope: 'scope.camera',
																success() {
																	console.log('授权成功')
																},
																fail() {
																	console	.log('用户点击取消')
																}
															})
														}
													},
													fail: function() {
														console.log("授权设置录音失败");
													}
												})

											} else if (res.cancel) {
												console.log('用户点击取消')
											}
										}
									})
								}
							})
						};
						if (!res.authSetting['scope.record']) { //获取录音权限
							wx.authorize({
								scope: 'scope.record',
								success() {
									console.log('授权成功')
								},
								fail() {
									wx.showModal({
										title: '提示',
										content: '尚未进行授权，部分功能将无法使用',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												wx.openSetting({
													success: (res) => {
														if (!res.authSetting[
																'scope.record']) {
															wx.authorize({
																scope: 'scope.record',
																success() {
																	console
																		.log(
																			'授权成功'
																		)
																},
																fail() {
																	console
																		.log(
																			'用户点击取消'
																		)
																}
															})
														}
													},
													fail: function() {
														console.log("授权设置录音失败");
													}
												})
											} else if (res.cancel) {
												console.log('用户点击取消')
											}
										}
									})
								}
							})
						}
					},
					fail(res) {

					}
				})
			},

		}
	}
</script>
